package edu.pinkhub.shiro_test.realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.pinkhub.shiro_test.entity.User;
import edu.pinkhub.shiro_test.service.UserService;
import edu.pinkhub.shiro_test.util.DigestsUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;


public class ShiroDBRealm extends AuthorizingRealm {
   @Autowired
   public UserService userService;

   public ShiroDBRealm(){
      //指定密码匹配方式
      HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(DigestsUtil.SHA1);
      //指定密码迭代次数
      matcher.setHashIterations(DigestsUtil.ITERATION);
      //匹配生效
      setCredentialsMatcher(matcher);
   }
   /**
    * 认证
    * @param token
    * @return
    * @throws AuthenticationException
    */
   @Override
   protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
      System.out.println("执行了doGetAuthenticationInfo（）方法");
      UsernamePasswordToken tk=(UsernamePasswordToken) token;
      QueryWrapper<User> wrapper = new QueryWrapper<User>();
      wrapper.eq("account",tk.getUsername());
      User user = userService.getOne(wrapper);
      if(user==null){
         return null;
      }
      Subject subject = SecurityUtils.getSubject();
      Session session = subject.getSession();
      session.setAttribute("loginUser",user);
      return new SimpleAuthenticationInfo(user,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),getName());
   }

   /**
    * 授权
    * @param principal
    * @return
    */
   @Override
   protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
      System.out.println("执行了doGetAuthorizationInfo()方法");
      SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
      Subject subject = SecurityUtils.getSubject();
      //认证成功后，返回信息的第一个参数
      User user = (User)subject.getPrincipal();
      System.out.println(user);
      List<String> permList = new ArrayList<>();
      String[] perms = user.getPerms().split(",");
      for(String perm:perms){
         permList.add(perm);
      }
      info.addStringPermissions(permList);
      return info;
   }
}
